<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        canvas {
            background-color: black;
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
</body>
<script id="ProjectionVS" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    uniform mat4 u_LightPvM4;
    uniform mat4 u_ModelM4;
    void main(){
        gl_Position = u_LightPvM4 * u_ModelM4 * a_Position;
    }
</script>
<script id="ProjectionFS" type="x-shader/x-fragment">
    precision mediump float;
    void main(){
         const vec4 bitShift = vec4(
            1.0,
            256.0,
            256.0 * 256.0,
            256.0 * 256.0 * 256.0
        );
        const vec4 bitMask = vec4(vec3(1.0 / 256.0), 0.0);
        vec4 depth = fract(gl_FragCoord.z * bitShift);
        depth -= depth.gbaa * bitMask;
        gl_FragColor = depth;
    }
</script>
<script id="ColorVS" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    attribute vec3 a_Normal;
    uniform mat4 u_PvM4;
    uniform mat4 u_ModelM4;
    uniform mat4 u_LightPvM4;
    varying vec3 v_Position;
    varying vec3 v_Normal;
    varying vec4 v_ClipposLight;
    void main(){
        vec4 worldPosi = u_ModelM4 * a_Position;
        gl_Position = u_PvM4 * worldPosi;
        v_Position = vec3(worldPosi);
        v_Normal = a_Normal;
        v_ClipposLight = u_LightPvM4 * worldPosi;
    }
</script>
<script id="ColorFS" type="x-shader/x-fragment">
    precision mediump float;

    uniform float u_Kd;
    uniform float u_Ks;
    uniform float u_Ka;
    uniform vec3 u_Color;
    uniform vec3 u_LdColor;
    uniform vec3 u_LsColor;
    uniform sampler2D u_ShadowMap;

    uniform vec3 u_Eye;
    uniform vec3 u_LightEye;
    uniform vec3 u_LightLookAt;
    uniform float u_LightIntensity;
    uniform vec2 u_LightFov;
    uniform vec2 u_LigthDist;

    varying vec3 v_Position;
    varying vec3 v_Normal;
    varying vec4 v_ClipposLight;

    bool isInShadow(){
        vec3 fragPos = (v_ClipposLight.xyz / v_ClipposLight.w) / 2.0 + 0.5;
        vec4 shadowFrag = texture2D(u_ShadowMap, fragPos.xy);
        const vec4 bitShift = vec4(
            1.0,
            1.0 / (256.0),
            1.0 / (256.0 * 256.0),
            1.0 / (256.0 * 256.0 * 256.0)
        );
        float depth = dot(shadowFrag, bitShift);
        return fragPos.z > depth + 1.0 / (256.0 * 4.0);
    }

    void main(){

        vec3 light = normalize(u_LightEye - u_LightLookAt);
        vec3 normal = normalize(v_Normal);
        vec3 eye = normalize(u_Eye - v_Position);
        vec3 h = normalize(eye + light);

        vec3 ld = u_Kd * u_LdColor * u_Color * max(0.0, dot(normal, light));
        vec3 ls = u_Ks * u_LsColor * pow(max(0.0, dot(normal, h)), 64.0);
        vec3 la = u_Ka * u_Color;

        vec3 pl = u_LightEye - v_Position;
        float r = length(cross(pl, light));
        float dist = dot(pl, light);
        float fov1 = tan(u_LightFov.x) * dist;
        float fov2 = tan(u_LightFov.y) * dist;
        float fallX = 1.0 - smoothstep(fov1, fov2, r);
        float fallY = 1.0 - smoothstep(u_LigthDist.x, u_LigthDist.y, dist);
        float fallB = step(0.0, dist);

        float intensity = u_LightIntensity * fallX * fallY * fallB;

        float shadow = isInShadow() ? 0.3 : 1.0;
        vec3 color = (ld + ls) * intensity * shadow + la;


        gl_FragColor = vec4(color, 1.0);
    }
</script>
<script type="module">
    import { Matrix4, Vector3, Color, PerspectiveCamera, Spherical } from '../js/three.module.js';
    import { CreateProgram, imgPromise } from '../js/Utils.js';
    import lib from '../js/ThreeLib.js';
    import CameraController from '../js/CameraController.js'
    import Poly from '../js/Poly4.js'
    import Control from '../js/Control.js'
    import Sphere from '../js/objs/Sphere.js'
    import Backdrop from '../js/Light/Backdrop.js'

    import Geo from '../js/Poly2/Geo.js'
    import Mat from '../js/Poly2/Mat.js'
    import Obj3D from '../js/Poly2/Obj3D.js'
    import Scene from '../js/Poly2/Scene.js'
    import Frame from '../js/Poly2/Frame.js'



    //#region gl
    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext("webgl", { antialias: true, });
    //#endregion

    //#region 
    const projectionProgram = CreateProgram(gl,
        document.querySelector('#ProjectionVS').innerText,
        document.querySelector('#ProjectionFS').innerText);

    const colorProgram = CreateProgram(gl,
        document.querySelector('#ColorVS').innerText,
        document.querySelector('#ColorFS').innerText);

    const scene = new Scene({ gl });
    scene.regProgram('color', {
        program: colorProgram,
        attribs: ['a_Position', 'a_Normal'],
        uniforms: [
            'u_PvM4', 'u_ModelM4',
            'u_Kd', 'u_Ks', 'u_Ka', 'u_Color', 'u_LdColor', 'u_LsColor',
            'u_Eye', 'u_LightEye', 'u_LightLookAt', 'u_LightIntensity', 'u_LightFov', 'u_LigthDist',
            'u_ShadowMap', 'u_LightPvM4',
        ],
    });
    const frame = new Frame({ gl });
    frame.regProgram('projection', {
        program: projectionProgram,
        attribs: ['a_Position'],
        uniforms: [
            'u_LightPvM4', 'u_ModelM4',
        ],
    });
    //#endregion

    const eye = new Vector3(0, 6, 20);
    const lookAt = new Vector3(0, 1.5, 0);
    const pvM4 = new Matrix4();
    const sphereModelM4 = new Matrix4();
    const camera = new PerspectiveCamera(45, canvas.width / canvas.height, 0.1, 100);
    const cameraController = new CameraController({
        gl, canvas, camera, pvMatrix: pvM4,
        eye, lookAt,
    })


    const sphere = new Sphere(1, 20, 20);
    const [sphereVertices, sphereNormals, sphereElements] = [
        sphere.vertices, sphere.normals, sphere.elements
    ];

    const backdrop = new Backdrop();
    const [backdropVertices, backdropNormals, backdropElements] = [
        backdrop.vertices, backdrop.normals, backdrop.elements
    ];

    const Kd = 0.7;
    const Ks = 0.3;
    const Ka = 0.3;
    const _Color = [1, 1, 1];
    const Ld_Color = [1, 1, 1];
    const Ls_Color = [1, 1, 1];

    //锥型灯
    const lightEye = new Vector3(0, 3, 5);
    const lightLookAt = new Vector3(0, 0, 0);
    const lightIntensity = 1;
    const ligthDist = [0, 20];
    const lightFov = [40 * Math.PI / 180, 70 * Math.PI / 180];
    const light = new PerspectiveCamera(140, canvas.width / canvas.height, 0.1, 10);
    light.position.copy(lightEye);
    light.lookAt(lightLookAt);
    light.updateMatrixWorld(true);
    const lightPvM4 = light.projectionMatrix.clone().multiply(light.matrixWorldInverse);



    //main
    {


        //创建投影
        const sphereTexture = createShpereTexture();
        const backdropTexture = createBackdropTexture();
        frame.add(sphereTexture)
        frame.add(backdropTexture)
        frame.draw();



        const sphereObj3D = createShpere(frame.texture);
        const backdropObj3D = createBackdrop(frame.texture);
        scene.add(sphereObj3D);
        scene.add(backdropObj3D);

    }

    function createShpereTexture() {
        return createTexture(sphereVertices, sphereElements, sphereModelM4);
    }
    function createBackdropTexture() {
        return createTexture(backdropVertices, backdropElements, new Matrix4());
    }
    function createTexture(vertices, elements, mm4) {
        return new Obj3D({
            geo: new Geo({
                data: {
                    'a_Position': { size: 3, array: new Float32Array(vertices) },
                },
                element: { array: new Uint16Array(elements) }
            }),
            mat: new Mat({
                program: 'projection',
                mode: ['TRIANGLES'],
                data: {
                    'u_LightPvM4': { type: 'uniformMatrix4fv', value: lightPvM4.elements },
                    'u_ModelM4': { type: 'uniformMatrix4fv', value: mm4.elements },
                }
            })
        });
    }

    function createShpere(texture) {
        return createObj3D(sphereVertices, sphereNormals, sphereElements, texture, sphereModelM4);
    }
    function createBackdrop(texture) {
        return createObj3D(backdropVertices, backdropNormals, backdropElements, texture, new Matrix4());
    }
    function createObj3D(vertices, normals, elements, texture, mm4) {
        return new Obj3D({
            geo: new Geo({
                data: {
                    'a_Position': { size: 3, array: new Float32Array(vertices) },
                    'a_Normal': { size: 3, array: new Float32Array(normals) },
                },
                element: { array: new Uint16Array(elements) }
            }),
            mat: new Mat({
                program: 'color',
                mode: ['TRIANGLES'],
                data: {
                    'u_PvM4': { type: 'uniformMatrix4fv', value: pvM4.elements },
                    'u_ModelM4': { type: 'uniformMatrix4fv', value: mm4.elements },
                    'u_Kd': { type: 'uniform1f', value: Kd },
                    'u_Ks': { type: 'uniform1f', value: Ks },
                    'u_Ka': { type: 'uniform1f', value: Ka },
                    'u_Color': { type: 'uniform3fv', value: _Color },
                    'u_LdColor': { type: 'uniform3fv', value: Ld_Color },
                    'u_LsColor': { type: 'uniform3fv', value: Ls_Color },
                    'u_Eye': { type: 'uniform3fv', value: [...eye] },
                    'u_LightEye': { type: 'uniform3fv', value: [...lightEye] },
                    'u_LightLookAt': { type: 'uniform3fv', value: [...lightLookAt] },
                    'u_LightIntensity': { type: 'uniform1f', value: lightIntensity },
                    'u_LigthDist': { type: 'uniform2fv', value: ligthDist },
                    'u_LightFov': { type: 'uniform2fv', value: lightFov },
                    'u_LightPvM4': { type: 'uniformMatrix4fv', value: lightPvM4.elements },
                },
                maps: {
                    'u_ShadowMap': { texture: texture }
                }
            })
        });
    }

    let a = -0.001;
    let v = 0;
    let y = 7;
    (function ani(time) {

        v += a;
        y += v;

        if (y < 0) {
            y = 0;
            v *= -1;
        }
        sphereModelM4.elements[13] = y;

        scene.setUniform('u_Eye', { value: [...eye] })

        //重新渲染贴图
        frame.draw();
        scene.draw();

        requestAnimationFrame(ani);
    })(0);


</script>

</html>